package com.htandroid.htandroid.sys;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskListListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbLogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.adapter.MyAdapter_listtab;
import com.htandroid.htandroid.adapter.MyAdapter_listtabm;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.tools.ToolDataProvider;
import com.htandroid.htandroid.views.LoadMoreListView;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by lkp on 2015/11/29.
 */
public class Base_lv_choose extends AbActivity implements AbPullToRefreshView.OnHeaderRefreshListener,
        AbPullToRefreshView.OnFooterLoadListener {
    public SwipeRefreshLayout swipeRefreshLayout;
    /*******************/
    public MyAdapter_listtabm sa;//数据样式
    public ArrayList<Map<String, Object>> adatperDataList = new ArrayList<Map<String, Object>>();
    //存放数据工具类
    public ToolDataProvider toolDataProvider;

    public final int send_email = 0; // 获取第一页的指令
    public final int LIST_GET_NEXT_PAGE = 1; //获取下一页的指令
    public final int LIST_GET_SEARCH_RESULT = 2; //获取下一页的指令

    public final int RESULT_LIST = 0; //显示数据列表
    public final int RESULT_SEARCH = 1; //显示搜索结果
    /*******************/
    public int resultMode;
    /*******************/
    public ImageView ivDeleteText; //搜索栏清空按钮
    /*******************/
    //下拉刷新用
    public static final String INDEX_START_TAG = "INDEX_START_TAG";
    public static final int INDEX_FIRST = 0;
    public static final int INDEX_MIDDLE = 1;
    public static final int INDEX_LAST = 2;
    public static final int INDEWX_NONE = 3;

    public static final int CMD_PRE_INDEX = 1001;
    public static final int CMD_NEXT_INDEX = 1002;
    public static final int CMD_INDEX = 1003;
    public int index;
    /*****************************/
    public String listtype = "0";//当前类型
    public MyApplication myApplication; //全局变量application
    public Boolean isShow = false;
    public InputMethodManager imm;
    public int icurrentrow = 0;//当前行

    private AbTitleBar mAbTitleBar = null;
    public View rightViewShare = null;
    public View rightViewRef = null;

    private AbPullToRefreshView mAbPullToRefreshView = null;
    public ListView mListView = null;
    private FrameLayout lvparent = null;
    private AbLoadDialogFragment mDialogFragment = null;

    private TextView tvTab1;
    private TextView tvTab2;
    private View linetab1;
    private View linetab2;
    private EditText etSearch;

    public String excelPath;
    public Button btn_share;
    public Button btn_ref;
    public String imgPath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onFooterLoad(AbPullToRefreshView view) {
        loadMoreTask();
    }

    @Override
    public void onHeaderRefresh(AbPullToRefreshView view) {
        refreshTask();
    }

    //初始化
    public void initview(String title) {
        myApplication = (MyApplication) abApplication;//获得我们的应用程序全局变量
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText(title);
        mAbTitleBar.setLogo(R.drawable.icon_back);
        mAbTitleBar.getLogoView().setLayoutParams(new LinearLayout.LayoutParams(58, 57));
        mAbTitleBar.getLogoView().setFocusable(true);
        mAbTitleBar.getLogoView().setFocusableInTouchMode(true);
        mAbTitleBar.setTitleBarBackground(R.color.common_title);
        mAbTitleBar.clearRightView();
        mAbTitleBar.setTitlePadding(86, 0, 0, 0);
        rightViewRef = mInflater.inflate(R.layout.ref, null);
        rightViewRef.setPadding(0, 0, 30, 0);
        mAbTitleBar.addRightView(rightViewRef);
        btn_ref = (Button) rightViewRef.findViewById(R.id.icon_ref);
        rightViewShare = mInflater.inflate(R.layout.share, null);
        mAbTitleBar.addRightView(rightViewShare);
        btn_share = (Button) rightViewShare.findViewById(R.id.icon_share);

        /*******************/
        // 工具类初始化
        toolDataProvider = new ToolDataProvider();
        /*******************/

        mAbPullToRefreshView = (AbPullToRefreshView) this.findViewById(R.id.mPullRefreshView);
        mListView = (ListView) this.findViewById(R.id.mListView);
        lvparent = (FrameLayout) findViewById(R.id.parent_fl);
        sa = new MyAdapter_listtabm(getApplicationContext(), adatperDataList, lvparent);
        mListView.setAdapter(sa);
        // TODO Auto-generated method stub

        tvTab1 = (TextView) findViewById(R.id.tab1);//未定价
        tvTab2 = (TextView) findViewById(R.id.tab2);//已定价
        linetab1 = findViewById(R.id.tab1_line);//未定价下划线
        linetab2 = findViewById(R.id.tab2_line);//已定价下划线
        //搜索框
        etSearch = (EditText) findViewById(R.id.etSearch);
        etSearch.clearFocus();
        imm = (InputMethodManager) getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
        //搜索清除
        ivDeleteText = (ImageView) findViewById(R.id.ivDeleteText);
        ivDeleteText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //清除文字
                etSearch.getText().clear();
                etSearch.clearFocus();
                //关闭软键盘
                adatperDataList.addAll(toolDataProvider.getFirstPage());
                //获取第一页
                sa.notifyDataSetChanged();
                //mHandler.sendEmptyMessage(LIST_GET_FIRST_PAGE);
                imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
                //显示删除图片
                ivDeleteText.setVisibility(View.VISIBLE);
            }
        });

        //切换监听
        tvTab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvTab1.setTextColor(getResources().getColor(R.color.yellow));
                linetab1.setBackgroundColor(getResources().getColor(R.color.yellow));
                tvTab2.setTextColor(getResources().getColor(R.color.white));
                linetab2.setBackgroundColor(getResources().getColor(R.color.white));
                listtype = "0";//状态一
                etSearch.getText().clear();
                getdata(0);
            }
        });

        tvTab2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvTab2.setTextColor(getResources().getColor(R.color.yellow));
                linetab2.setBackgroundColor(getResources().getColor(R.color.yellow));
                tvTab1.setTextColor(getResources().getColor(R.color.white));
                linetab1.setBackgroundColor(getResources().getColor(R.color.white));
                listtype = "1";//状态２
                etSearch.getText().clear();
                getdata(0);
            }
        });

//        // 设置卷内的颜色
//        swipeRefreshLayout.setColorSchemeResources(
//                android.R.color.holo_blue_bright,
//                android.R.color.holo_green_light,
//                android.R.color.holo_orange_light,
//                android.R.color.holo_red_light);
//        // 设置下拉刷新监听
//        //swipeRefreshLayout.setOnRefreshListener(this);

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 0) {
                    ivDeleteText.setVisibility(View.INVISIBLE);
                    adatperDataList.addAll(toolDataProvider.getFirstPage());
                    //获取第一页
                    sa.notifyDataSetChanged();
                    //mHandler.sendEmptyMessage(LIST_GET_FIRST_PAGE);
                } else {
                    ivDeleteText.setVisibility(View.VISIBLE);
                    String keyword = etSearch.getText().toString().trim();
                    adatperDataList.clear();
                    adatperDataList.addAll(toolDataProvider.getSearch(keyword));
                    sa.notifyDataSetChanged();
                    //mHandler.sendEmptyMessage(LIST_GET_SEARCH_RESULT);
                }
            }
        });
    }

    // 将excel图标保存到sd卡
    public void writeImg(String file) {
        File filePath = new File(file);
        //得到图片对象
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.excel);
        FileOutputStream fos = null;
        try {
            //创建输出流
            fos = new FileOutputStream(filePath);
            //解析图片
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadList() {
        mAbPullToRefreshView.setOnHeaderRefreshListener(this);
        mAbPullToRefreshView.setOnFooterLoadListener(this);

        // 设置进度条的样式
        mAbPullToRefreshView.getHeaderView().setHeaderProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));
        mAbPullToRefreshView.getFooterView().setFooterProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));
        refreshTask();
    }

    public void refreshTask() {
        AbLogUtil.prepareLog(base_index.class);
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();

        item.setListener(new AbTaskListListener() {
            @Override
            public List<?> getList() {
                List<Map<String, Object>> newList = null;
                try {
                    Thread.sleep(1000);
                    newList = toolDataProvider.getFirstPage();
                } catch (Exception e) {
                }
                return newList;
            }

            @Override
            public void update(List<?> paramList) {
                AbDialogUtil.removeDialog(Base_lv_choose.this);
                //AbLogUtil.d(base_index.class, "返回", true);
                List<Map<String, Object>> newList = (List<Map<String, Object>>) paramList;
                adatperDataList.clear();
                if (newList != null && newList.size() > 0) {
                    adatperDataList.addAll(newList);
                    sa.notifyDataSetChanged();
                    newList.clear();
                }
                mAbPullToRefreshView.onHeaderRefreshFinish();
            }
        });
        mAbTask.execute(item);
    }

    public void loadMoreTask() {
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListListener() {

            @Override
            public void update(List<?> paramList) {
                AbDialogUtil.removeDialog(Base_lv_choose.this);
                List<Map<String, Object>> newList = (List<Map<String, Object>>) paramList;
                if (newList != null && newList.size() > 0) {
                    adatperDataList.addAll(newList);
                    sa.notifyDataSetChanged();
                    newList.clear();
                }
                mAbPullToRefreshView.onFooterLoadFinish(newList.size());
            }

            @Override
            public List<?> getList() {
                List<Map<String, Object>> newList = null;
                try {
                    Thread.sleep(1000);
                    newList = toolDataProvider.getNext();
                } catch (Exception e) {
                    newList.clear();
                    AbToastUtil.showToastInThread(getApplicationContext(), e.getMessage());
                }
                return newList;
            }
        });
        mAbTask.execute(item);
    }

    //单独处理一个初始化,便于重写的初始化事件处理
    public void initview2() {

    }

    /********************************************/
    //获取数据,因为每个列表获取数据方式不一样.所以这个函数都需要重写
    public void getdata(int page) {

    }

    //行选择事件
    public void linechoose(String ctype, int id) {
        //m多选,r单选
        if (ctype.equals("m")) {
            //多选,第一次选中,第二次取消
            sa.getIsSelected().put(id, !sa.getIsSelected().get(id));
        } else {
            //单选
            //先恢复当前行选中
            sa.getIsSelected().put(icurrentrow, false);
            //重新选中
            sa.getIsSelected().put(id, true);
        }
        icurrentrow = id;
        sa.notifyDataSetChanged();
    }

//    public void btn_ref(View v) {
//        getdata(0);
//    }

    /*******
     * 刷新
     *******************/
//    @Override
//    public void onLoadMore() {
//        if (resultMode == RESULT_LIST) {
//            if (toolDataProvider.hasNext()) { //判断有能够显示的内容
//                mHandler.sendEmptyMessage(LIST_GET_NEXT_PAGE);
//            } else {
//                lv.setLoadNoMore();
//            }
//        }
//        if (resultMode == RESULT_SEARCH) {
//            // 什么事都不做
//        }
//        /*
//        if (resultMode == RESULT_LIST) {
//            if (toolDataProvider.hasNext()) { //判断有能够显示的内容
//                mHandler.sendEmptyMessage(LIST_GET_NEXT_PAGE);
//            } else {
//                Toast.makeText(getApplicationContext(), "没有更多", Toast.LENGTH_SHORT).show();
//            }
//        }
//        if (resultMode == RESULT_SEARCH) {
//            // 什么事都不做
//        }*/
//    }

//    @Override
//    public void onRefresh() {
//        getdata(0);
//    }
}
